package com.hg.concurent.demo5;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil;

import java.util.concurrent.CountDownLatch;

/**
 * 跑步比赛
 * created by skh on 2019/12/21
 */
public class RunDemo {

	//5名选手,必选所有先到起点准备后,再同时开跑,最后所有人到达终点后,比赛结束
	public static void main(String[] args) throws InterruptedException {
		CountDownLatch startLatch = new CountDownLatch(1);
		CountDownLatch endLatch = new CountDownLatch(5);

		new Thread(()->{
			try {
				new Player(startLatch, endLatch).run();
			} catch (Exception e) {
				e.printStackTrace();
			}
		},"A").start();

		new Thread(()->{
			try {
				new Player(startLatch, endLatch).run();
			} catch (Exception e) {
				e.printStackTrace();
			}
		},"B").start();

		new Thread(()->{
			try {
				new Player(startLatch, endLatch).run();
			} catch (Exception e) {
				e.printStackTrace();
			}
		},"C").start();

		new Thread(()->{
			try {
				new Player(startLatch, endLatch).run();
			} catch (Exception e) {
				e.printStackTrace();
			}
		},"D").start();

		new Thread(()->{
			try {
				new Player(startLatch, endLatch).run();
			} catch (Exception e) {
				e.printStackTrace();
			}
		},"E").start();

		ThreadUtil.sleep(1000);
		System.out.println("裁判清点人数");
		startLatch.countDown();

		endLatch.await();

		System.out.println("所有选手到达终点,比赛结束");

	}

}

class Player {

	private CountDownLatch startLatch;

	private CountDownLatch downLatch;

	public Player(CountDownLatch startLatch, CountDownLatch downLatch) {
		this.startLatch = startLatch;
		this.downLatch = downLatch;
	}

	public void run() throws Exception{
		System.out.println(Thread.currentThread().getName() + "准备完毕");
		startLatch.await();
		System.out.println(Thread.currentThread().getName() + "开始奔跑");
		ThreadUtil.sleep(RandomUtil.randomInt(1000,3000));
		System.out.println(Thread.currentThread().getName() + "到达终点");
		downLatch.countDown();
	}
}
